package com.jbp.service;

import com.alibaba.fastjson.JSON;
import com.jbp.domin.HamsterNotice;
import com.jbp.domin.LotteryNotice;
import com.jbp.domin.WhacMoleReq;
import com.jbp.model.Gift;
import com.jbp.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

//推送服务
@Service
public class PushService {

    private final ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);

    @Autowired
    private TecentMsgService tecentMsgService;
    @Autowired
    private UserService userService;
    @Autowired
    private RoomUserWheatService roomUserWheatService;
    /**
     * 抽到大奖
     * 推送给在房间的所有用户
     * */
    public void bigLucky(Integer userId, int poolPrice, List<Gift> giftList) {
        try {
            User user = userService.getById(userId);
            List<String> userIds = null;
            for (Gift gift : giftList) {
                boolean flag = false;
                if (gift.getCoin()>=500) {
                    flag = true;
                } else if (poolPrice==1000) {
                    flag = true;
                } else if (poolPrice==2000) {
                    flag = true;
                } else if (poolPrice==200) {
                    flag = true;
                } else if (gift.getType()!=0) {
                    flag = true;
                }
                if (flag) {
                    LotteryNotice notice = LotteryNotice.builder()
                            .giftId(gift.getId())
                            .giftName(gift.getName())
                            .giftType(gift.getType())
                            .giftImage(gift.getImgUrl())
                            .giftCoin(gift.getCoin())
                            .giftCount(gift.getNum())
                            .userName(user.getName())
                            .userId(user.getId())
                            .userLevel(user.getLevel())
                            .poolPrice(poolPrice)
                            .build();

                    //查询所有在房间用户id
                    if (CollectionUtils.isEmpty(userIds)) {
                        userIds = roomUserWheatService.allUserIds().stream().map(id -> String.valueOf(id)).collect(Collectors.toList());
                    }
                    /*for (int j = 0; j < 600; j++) {
                        if (userIds!=null && userIds.size()>0) {
                            for (int i=0; i<userIds.size(); i=i+500) {//单词最多同时发500个人
                                int end = Math.min(i+500, userIds.size());
                                List<String> curIds = userIds.subList(i, end);

                                HashMap<Object, Object> map = new HashMap<>();
                                map.put("type", 2);
                                map.put("data", notice);
                                new Thread(() -> tecentMsgService.sendMsgsFromManger(curIds, JSON.toJSONString(map), "administrator")).start();
                            *//*executor.submit(() -> {
                                tecentMsgService.sendMsgsFromManger(curIds, JSON.toJSONString(map), "administrator");
                            });*//*
                            }
                        }
                    }*/
                    if (userIds!=null && userIds.size()>0) {
                        for (int i=0; i<userIds.size(); i=i+500) {//单词最多同时发500个人
                            int end = Math.min(i+500, userIds.size());
                            List<String> curIds = userIds.subList(i, end);

                            HashMap<Object, Object> map = new HashMap<>();
                            map.put("type", 2);
                            map.put("data", notice);
                            new Thread(() -> tecentMsgService.sendMsgsFromManger(curIds, JSON.toJSONString(map), "administrator")).start();
                            /*executor.submit(() -> {
                                tecentMsgService.sendMsgsFromManger(curIds, JSON.toJSONString(map), "administrator");
                            });*/
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 机器人中奖消息发送
     * @param userId
     * @param poolPrice
     * @param giftList
     */
    public void bigLuckyRob(Integer userId, int poolPrice, List<Gift> giftList, int counts) {
        try {
            User user = userService.getById(userId);
            List<String> userIds = null;
            for (Gift gift : giftList) {
                boolean flag = false;
                if (gift.getCoin()>=500) {
                    flag = true;
                } else if (poolPrice==1000) {
                    flag = true;
                } else if (poolPrice==2000) {
                    flag = true;
                } else if (poolPrice==200) {
                    flag = true;
                } else if (gift.getType()!=0) {
                    flag = true;
                }
                if (flag) {
                    LotteryNotice notice = LotteryNotice.builder()
                            .giftId(gift.getId())
                            .giftName(gift.getName())
                            .giftType(gift.getType())
                            .giftImage(gift.getImgUrl())
                            .giftCoin(gift.getCoin())
                            .giftCount(gift.getNum())
                            .userName(user.getName())
                            .userId(user.getId())
                            .userLevel(user.getLevel())
                            .poolPrice(poolPrice)
                            .build();

                    //查询所有在房间用户id
                    if (CollectionUtils.isEmpty(userIds)) {
                        userIds = roomUserWheatService.allUserIds().stream().map(id -> String.valueOf(id)).collect(Collectors.toList());
                    }
                    if (userIds!=null && userIds.size()>0) {
                        for (int i=0; i<userIds.size(); i=i+500) {
                            int end = Math.min(i+500, userIds.size());
                            List<String> curIds = userIds.subList(i, end);

                            HashMap<Object, Object> map = new HashMap<>();
                            map.put("type", 2);
                            map.put("data", notice);
//                                new Thread(() -> tecentMsgService.sendMsgsFromManger(curIds, JSON.toJSONString(map), "administrator")).start();
                            /*executor.submit(() -> {
                                // 延迟1000/counts
                                Long times = (long) (1000/counts);
                                try {
                                    Thread.sleep(times);
                                } catch (InterruptedException e) {
                                    throw new RuntimeException(e);
                                }
                                tecentMsgService.sendMsgsFromManger(curIds, JSON.toJSONString(map), "administrator");
                            });*/
                            new Thread(() -> {
                                try {
                                    // 延迟1000/counts
                                    Long times = (long) (1000/counts);
                                    Thread.sleep(times);
                                    // 执行你的操作
//                                    System.out.println("执行操作，延迟3秒后");
                                    tecentMsgService.sendMsgsFromManger(curIds, JSON.toJSONString(map), "administrator");
                                } catch (InterruptedException e) {
                                    Thread.currentThread().interrupt(); // 重置中断状态
                                    System.out.println("线程被中断");
                                }
                            }).start();
                        }
                    }
                    /*if (userIds!=null && userIds.size()>0) {
                        for (int i=0; i<userIds.size(); i=i+500) {
                            int end = Math.min(i+500, userIds.size());
                            List<String> curIds = userIds.subList(i, end);

                            HashMap<Object, Object> map = new HashMap<>();
                            map.put("type", 2);
                            map.put("data", notice);
                            new Thread(() -> tecentMsgService.sendMsgsFromManger(curIds, JSON.toJSONString(map), "administrator")).start();
                            *//*executor.submit(() -> {
                                // 延迟1000/counts
                                Long times = (long) (1000/counts);
                                try {
                                    Thread.sleep(times);
                                } catch (InterruptedException e) {
                                    throw new RuntimeException(e);
                                }
                                tecentMsgService.sendMsgsFromManger(curIds, JSON.toJSONString(map), "administrator");
                            });*//*
                            *//*new Thread(() -> {
                                try {
                                    // 延迟1000/counts
                                    Long times = (long) (1000/counts);
                                    Thread.sleep(times);
                                    // 执行你的操作
//                                    System.out.println("执行操作，延迟3秒后");
                                    tecentMsgService.sendMsgsFromManger(curIds, JSON.toJSONString(map), "administrator");
                                } catch (InterruptedException e) {
                                    Thread.currentThread().interrupt(); // 重置中断状态
                                    System.out.println("线程被中断");
                                }
                            }).start();*//*
                        }
                    }*/
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 打死地鼠，中奖，发消息到房间中的用户
     * @param userId
     * @param result
     */
    public void hamsterLucky(Integer userId, int result, WhacMoleReq whacMoleReq){

        try {
            User user = userService.getById(userId);
            HamsterNotice notice = HamsterNotice.builder()
                    .hamsterKind(Integer.parseInt(whacMoleReq.getHamsterKind()))
                    .userName(user.getName())
                    .userId(user.getId())
                    .userLevel(user.getLevel())
                    .roomId(whacMoleReq.getRoomId())
                    .values(result)
                    .build();

            //查询所有在房间用户id
//            List<String> userIds = roomUserWheatService.getUserIds(whacMoleReq.getRoomId()).stream().map(id -> String.valueOf(id)).collect(Collectors.toList());
            List<String> userIds = roomUserWheatService.allUserIds().stream().map(id -> String.valueOf(id)).collect(Collectors.toList());
            if (userIds != null && userIds.size() > 0) {
                for (int i=0; i<userIds.size(); i=i+500){
                    int end = Math.min(i+500, userIds.size());
                    List<String> curIds = userIds.subList(i, end);
                    HashMap<Object, Object> map = new HashMap<>();
                    map.put("type", "hamster");
                    map.put("data", notice);
                new Thread(() -> tecentMsgService.sendMsgsFromManger(userIds, JSON.toJSONString(map), "administrator")).start();
                    /*executor.submit(() -> {
                        tecentMsgService.sendMsgsFromManger(curIds, JSON.toJSONString(map), "administrator");
                    });*/
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
